package com.wx.mythread.stopthread.volatiledemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 用中断来修复刚才volatile的阻塞问题
 *
 */
public class WrongWayVolatileFixed {

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatileFixed fixed = new WrongWayVolatileFixed();
        BlockingQueue blockingQueue = new ArrayBlockingQueue(10);

        Producer producer = fixed.new Producer(blockingQueue);
        Thread thread = new Thread(producer);
        thread.start();
        Thread.sleep(1000);

        Consumer consumer = fixed.new Consumer(blockingQueue);
        while (consumer.needMoreNums()) {
            System.out.println(blockingQueue.take() + "被消费了");
            Thread.sleep(100);
        }
        System.out.println("消费者不需要更多的数据了");
        thread.interrupt();
        // producer.canceled  = true;
        // System.out.println(producer.canceled);
    }

    class Producer implements Runnable{

        private BlockingQueue storage;


        public Producer(BlockingQueue storage) {
            this.storage = storage;
        }

        @Override
        public void run() {
            int num = 0;
            try {
                while (num < 100000 && !Thread.currentThread().isInterrupted()){
                    if (num % 100 == 0){
                        //put操作慢的时候，线程会阻塞
                        storage.put(num);
                        System.out.println(num + "是100的倍数，放到仓库中");
                    }
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("生成者停止运行");
            }
        }
    }

    class Consumer{
        private BlockingQueue storage;

        public Consumer(BlockingQueue storage) {
            this.storage = storage;
        }

        public boolean needMoreNums(){
            if (Math.random() > 0.95){
                return false;
            }
            return true;
        }
    }
}
